package com.mmall.concurerency.example.count;

import com.mmall.concurerency.annoations.NoThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
/**
 * count{}4998  测试main方法，每次打印的结果都不相同，所以这是一个线程不安全的类。
 */
@NoThreadSafe   //标注为线程不安全的类
public class CountExample1 {

    private static int clientTotal = 5000;  //请求总数
    private static int threadTotal = 200;    //同时线程并发量

    public static int count = 0;

    public static void main(String[] args) throws  Exception {
        ExecutorService  executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            //1.8 Lambda  表达式
            executorService.execute(()->{
                try{
                    //信号量50，有信号量才去执行add 否则就阻塞在这里
                    semaphore.acquire();
                    add();
                    semaphore.release();
                }catch (Exception e){
                    log.error("exception",e);
                }
                //闭锁，每执行完一次后，都减一操作
                countDownLatch.countDown();
            });
        }
        //这个方法必须保持 countDownLatch.countDown(); 执行 5000 次，
        countDownLatch.await();
        //当执行完了线程不再用就关闭掉
        executorService.shutdown();
        //当所有的线程结束完了后打印出数据
        log.error("count{}"+ count);
    }

    /**
     * 这里是线程不安全的主源
     */
    public static void add(){
        count ++ ;
    }
}
